package br.ufpb.di.ppgi.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.caelum.vraptor.ioc.Component;

@Component
@ApplicationScoped
public class PropertiesUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtil.class);
    private static final String DEFAULT_BUNDLE_NAME = "sim-conf";
    
	private final ResourceBundle bundle;
	
	public PropertiesUtil() {
		bundle = createBundle();
	}
	
	private ResourceBundle createBundle() {
        try {
			return ResourceBundle.getBundle(DEFAULT_BUNDLE_NAME);
		} catch (MissingResourceException ex) {
			LOGGER.warn("couldn't find configuration bundle, creating an empty one", ex);
			return createEmptyBundle();
		}
	}
	
	private ResourceBundle createEmptyBundle() {
		try {
			return new PropertyResourceBundle(new ByteArrayInputStream(new byte[0]));
		} catch (IOException e) {
			LOGGER.warn("It shouldn't happen. Please report this bug", e);
			return null;
		}
	}
	
	public String getString(String key) {
		try {
			return bundle.getString(key);
		} catch(MissingResourceException ex) {
			LOGGER.warn(String.format("couldn't find key=\"%s\" from configuration bundle", key), ex);
			return null;
		}
	}
	
	public Integer getInteger(String key) {
		String content = getString(key);
		if (content == null)
			return null;
		content = content.trim();
		if (content.isEmpty())
			return null;
		try {
			return Integer.valueOf(content);
		} catch (NumberFormatException ex) {
			LOGGER.error(String.format("the value for key=\"%s\" is not a number",key),ex);
			return null;
		}
	}
	
	public boolean getBoolean(String key) {
		String content = getString(key);
		try {
			return Boolean.valueOf(content);
		} catch (NumberFormatException ex) {
			LOGGER.error(String.format("the value for key=\"%s\" is not a boolean",key),ex);
			return false;
		}
	}
	
	private DateUtil dateUtil = DateUtil.getInstance();
	
	public Date getDate(String key) {
		try {
			return dateUtil.toDate(getString(key));
		} catch (IllegalArgumentException ex) {
			LOGGER.error(String.format("the value for key=\"%s\" is not a date",key),ex);
			return null;
		}
	}
}
